package com.rzico.sbl.ui.report.dispatch

import android.text.Editable
import android.text.InputFilter
import android.text.TextWatcher
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import com.google.gson.Gson
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lzg.extend.jackson.JsonUtil
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportDispatchRottenBinding
import com.rzico.sbl.model.DispatchRotten
import com.rzico.sbl.model.ReportGoodsData
import com.rzico.sbl.ui.report.other.goToDispatchThird
import com.rzico.sbl.viewmodel.ReportDispatchViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.other.DecimalNumberFilter
import com.xinnuo.common.listener._TextWatcher
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.helper.doubleValue
import com.xinnuo.common.helper.intValue
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter
import org.json.JSONArray
import org.json.JSONObject

class ReportDispatchRottenActivity : BaseActivity(R.layout.activity_report_dispatch_rotten) {

    private val mBinding by lazy { ActivityReportDispatchRottenBinding.bind(getRootView()) }

    private lateinit var mTotalView: TextView
    private lateinit var mOrderSn: String
    private lateinit var mShippingId: String
    private lateinit var mShippingSn: String

    private val mRottenList = ArrayList<DispatchRotten>()
    private var mRottenPirce = "0.00"

    override fun getViewModel() = get<ReportDispatchViewModel>()

    override fun initData() {
        initTitle(title = "烂桶")

        initLayout()

        getData()
    }

    private fun initLayout() {
        mBinding.listLayout.apply {
            swipeRefresh.isEnabled = false

            recycleList.also { layout ->
                layout.addItemDecoration(SpaceTBDecoration())

                mAdapter = SlimAdapter.creator()
                    .register<DispatchRotten>(R.layout.item_report_dispatch_rotten) { jector, bean, index ->
                        jector.apply {
                            text(R.id.item_rotten_name, bean.name)
                            text(R.id.item_rotten_price, bean.price.formatDecimal())

                            // 烂桶数量
                            with<EditText>(R.id.item_rotten_count) {
                                if (it.tag != null && it.tag is TextWatcher) {
                                    it.removeTextChangedListener(it.tag as TextWatcher)
                                }

                                it.setText(bean.quantity)
                                it.setSelection(it.text.length)

                                val textWatcher = object : _TextWatcher() {
                                    override fun afterTextChanged(s: Editable) {
                                        bean.quantity = s.toString()
                                        bean.subPrice =
                                            (bean.quantity.intValue * bean.price.doubleValue).formatDecimal()
                                        getView<EditText>(R.id.item_rotten_amount).setText(bean.subPrice)
                                        totalAmount()
                                    }
                                }
                                it.addTextChangedListener(textWatcher)
                                it.tag = textWatcher
                            }

                            // 烂桶金额
                            with<EditText>(R.id.item_rotten_amount) {
                                if (it.tag != null && it.tag is TextWatcher) {
                                    it.removeTextChangedListener(it.tag as TextWatcher)
                                }

                                it.filters =
                                    arrayOf(DecimalNumberFilter(), InputFilter.LengthFilter(8))
                                it.setText(bean.subPrice.formatDecimal())
                                it.setSelection(it.text.length)

                                val textWatcher = object : _TextWatcher() {
                                    override fun afterTextChanged(s: Editable) {
                                        bean.subPrice = s.toString()
                                        totalAmount()
                                    }
                                }
                                it.addTextChangedListener(textWatcher)
                                it.tag = textWatcher
                            }

                            clicked(R.id.item_rotten_del) {
                                mRottenList.removeAt(index)
                                mAdapter.apply {
                                    notifyItemRemoved(index)
                                    notifyItemRangeChanged(index, mRottenList.size - index)
                                }

                                totalAmount()
                            }
                        }
                    }
                    .attachTo(layout)
                    .addFooter(baseContext, R.layout.footer_report_rotten) { _, view ->
                        view.also { mTotalView = it.find(R.id.rotten_total) }
                            .find<Button>(R.id.rotten_add)
                            .oneClick {
                                startActivityEx<ReportDispatchGoodsActivity>(
                                    "orderSn" to mOrderSn
                                )
                            }
                    }
            }
        }
    }

    override fun initListener() {
        mOrderSn = intent.getExtra("orderSn")
        mShippingId = intent.getExtra("shipId")
        mShippingSn = intent.getExtra("shippingSn")

        mBinding.apply {
            btSkip.oneClick {
                goToDispatchThird(
                    "shipId" to mShippingId,
                    "orderSn" to mOrderSn,
                    "shippingSn" to mShippingSn
                )

                finishView()
            }

            btNext.oneClick {
                getViewModel()
                    .dispatchRotten(
                        "sn" to mShippingSn,
                        "swapPrice" to mRottenPirce,
                        "body" to Gson().toJson(mRottenList.filter { it.quantity.intValue > 0 })
                    )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            goToDispatchThird(
                                "shipId" to mShippingId,
                                "orderSn" to mOrderSn,
                                "shippingSn" to mShippingSn
                            )
                        }
                    )
            }
        }

        LiveEventBus
            .get("rottenGoods", ReportGoodsData::class.java)
            .observe(this) { item ->
                getViewModel()
                    .delay {
                        if (mRottenList.none { it.id == item.productId }) {
                            mRottenList.add(
                                DispatchRotten(
                                    id = item.productId.orEmpty(),
                                    name = item.name,
                                    price = item.phPrice.orEmpty("0.00")
                                )
                            )

                            mAdapter.notifyDataSetChanged()
                        } else
                            showToast("已存在该商品，请添加其他商品")
                    }
            }
    }

    /**
     * 烂桶商品列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .dispatchPay(mShippingSn)
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = { result ->
                    val obj = JSONObject(result)

                    val objItems = obj.optJSONArray("shippingSwaps") ?: JSONArray()
                    mRottenList.clear()
                    mRottenList.addItems(
                        JsonUtil.toList(
                            objItems.toString(),
                            DispatchRotten::class.java
                        )
                    )

                    totalAmount()

                    mAdapter.setDataList(mRottenList)
                }
            )
    }

    /**
     * 烂桶合计计算
     */
    private fun totalAmount() = kotlin.run {
        val realList = mRottenList.filter { it.quantity.intValue > 0 }

        mTotalView.text =
            when {
                realList.size == 1 ->
                    realList[0]
                        .subPrice
                        .formatDecimal()
                        .also { mRottenPirce = it }
                realList.size > 1 ->
                    "${
                        realList.joinToString(" + ") {
                            it.subPrice.formatDecimal()
                        }
                    } = ${
                        realList
                            .sumOf { it.subPrice.doubleValue }
                            .formatDecimal().also { mRottenPirce = it }
                    }"
                else -> "0.00".also { mRottenPirce = it }
            }

    }

}